from django.shortcuts import render
from django.views.generic.base import View
from django.http import HttpResponse
import re,json
from .models import Users
from mgproject.utils.exceptions import Forbbiden
from django.db import DatabaseError
from django.contrib.auth import login
from django.views.generic.base import reverse
from django.http import JsonResponse
from django.contrib.auth import logout
from django.shortcuts import redirect
from django import http
from django.contrib.auth import authenticate
# Create your views here.
class EmailView(View):
    def post(self,request):
        '''
        保存当前用户邮箱地址
        '''
        params_str = request.body.decode()
        if params_str:
            p_dict = json.loads(params_str)
        count =Users.objects.filter(id=p_dict['userid']).update(email=p_dict['email'])
        if count:
            return JsonResponse({'code': 200, 'errormsg':'OK'})
        return JsonResponse({'code': 500, 'errormsg': '保存邮箱地址失败！'})

class RegisterView(View):
    def get(self,request):
        return render(request,'userapp/register.html')
    def post(self,request):
        #接受表单数据
        username=request.POST.get('username','')
        phone=request.POST.get('phone','')
        password=request.POST.get('password','')
        #参数校验
        #判断参数是否为空
        if not all([username,phone,password]):
            raise Forbbiden('参数不能为空')
        if not re.match(r'^[A-Za-z]{5,6}$',username):
             raise Forbbiden('请输入5-6位的用户名')
        if not re.match(r'^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$',phone):
            raise Forbbiden('请输入正确的手机号')
        if not re.match(r'[a-zA-Z0-9]{3,8}',password):
            raise Forbbiden('请按格式输入密码')



        #将数据存入数据库
        #try:
        user=Users.objects.create_user(username=username,password=password,phone=phone)

        # except DatabaseError :
        #     return render(request,'userapp/register.html',{'reg_error_msg':'注册失败'})
        #状态保持
        login(request,user)
        #返回响应结果
        return redirect(reverse('newsapp:index'))
#校验用户是否重复登录
class UserNameCount(View):
    def get(self,request,username):
        '''
        查询当前用户名的记录数
        '''
        count=Users.objects.filter(username=username).count()
        return JsonResponse({'code':200,'errormsg':'ok','count':count})
#校验电话号码是否重复注册
class PhoneCount(View):
    def get(self,request,phone):
        '''
        查询当前手机号的记录数
        '''
        count=Users.objects.filter(phone=phone).count()
        return JsonResponse({'code':200,'errormsg':'ok','count':count})


#用户退出登录
class LogoutView(View):
    def get(self,request):
        '''
        用户退出功能
        '''
        logout(request)
        return redirect(reverse('newsapp:index'))
#用户登录
class LoginView(View):
    def post(self,request):
        '''
        处理登录请求
        '''
        #接收参数
        username=request.POST.get('username')
        password=request.POST.get('password')
        remember=request.POST.get('remember')
        #校验参数
         #非空校验
        if not all([username,password,remember]):
            return http.HttpResponseForbidden('缺少必要参数')
        #认证参数格式是否正确
        if not re.match(r'^[a-zA-Z][A-Za-z0-9-]{4,7}',username):
            return http.HttpResponseForbidden('请输入5-8位字符')
        if not re.match(r"^[0-9a-zA-Z]{3,8}",password):
            return http.HttpResponseForbidden('密码格式错误')
        #认证参数值是否正确
        user=authenticate(username=username,password=password)
        if user is None:
            return render(request,'userapp/login.html',{'login_error':'用户名密码错误'})

        #状态保持
        login(request,user)
        if remember !='yes':
            request.session.set_expiry(0)#关闭浏览器失效
        else:
            request.session.set_expiry(None)#默认两周
        #响应结果
        return redirect(reverse('newsapp:index'))
    def get(self,request):
        '''
        显示登录首页
        '''
        return render(request,'userapp/login.html')
class UserCenterView(View):
    def get(self,request):
        """
        用户中心
        """
        #return render(request,'userapp/user_center.html')
        # if request.user.is_authenticated:
        return render(request,'userapp/user_center.html')
        # else:
        #     return redirect(reverse('newsapp:index'))